'''
Created on Apr 26, 2009

@author: tzoght
'''

import sys
import os
import datetime
from com.tzoght.financial.investorline import * 
from datetime import * 

# 2008-11-28
def getDate(dateStr):
    date = datetime.strptime(dateStr,"%Y-%m-%d")
    return date

# 2008-11-03,2008-11-06,Buy,CDN OIL SANDS TR NEW UNIT,COS.UN,1000,31.50,CDN,-31509.95,CDN
def createTransactionsFromTokens(tokens):
    transactions = []
    for tokenItem in tokens:
        transactionDate = None
        settlementDate = None
        type = None
        symbol = None
        equityName = None
        quantity = None
        price = None
        currency = None
        total = None
        if (tokenItem[0] != ''):
            transactionDate = getDate(tokenItem[0])
        if (tokenItem[1] != ''):
            settlementDate = getDate(tokenItem[1])
        if (tokenItem[2] != ''):
            type = tokenItem[2]
        if (tokenItem[3] != ''):
            equityName = tokenItem[3]
        if (tokenItem[4] != ''):
            symbol = tokenItem[4]
        if (tokenItem[5] != ''):
            quantity = int(tokenItem[5])     
        if (tokenItem[6] != ''):
            price = float(tokenItem[6]) 
        if (tokenItem[7] != ''):
            currency = tokenItem[7]     
        if (tokenItem[8] != ''):
            total = float(tokenItem[8])               
        tx = InstrumentTransaction(transactionDate,settlementDate,type,symbol,equityName,quantity,price,currency,total) 
        print tx
        transactions.append(tx)   
    return transactions

def parseInitialHoldings(holdingsFileToParse):
    holdingsMap = {}
    F = open(holdingsFileToParse)
    lines = F.readlines()
    tokensList = [] 
    for line in lines:
        tokens = line.split(',')
        tokenItem = (tokens[0].strip(),tokens[1].strip(),tokens[2].strip(),tokens[3].strip())
        tokensList.append(tokenItem)
    for tokenItem in tokensList:
        symbol = None
        quantity = None
        price = None
        total = None
        if (tokenItem[0] != ''):
            symbol = tokenItem[0]
        if (tokenItem[1] != ''):
            quantity = int(tokenItem[1])
        if (tokenItem[2] != ''):
            price = float(tokenItem[2])
        if (tokenItem[3] != ''):
            total = float(tokenItem[3])              
        h = InstrumentHolding(symbol, "", quantity, price, total, 'CAD') 
        holdingsMap[symbol] = h     
    return holdingsMap
    
def tokenize(fileToParse):
    F = open(fileToParse)
    lines = F.readlines()
    tokensList = []
    # Transaction Date,Settlement Date,Activity Description,Description,Symbol,Quantity,Price,Currency,Total Amount,Currency
    for line in lines:
        if (line == '\n'):
            continue
        if (line.startswith( "Transaction" )):
            continue 
        if (line.startswith( "---" )):
            continue 
        tokens = line.split(',')
        tokenItem = (tokens[0].strip(),tokens[1].strip(),tokens[2].strip(),tokens[3].strip(),tokens[4].strip()\
                     ,tokens[5].strip(),tokens[6].strip(),tokens[7].strip(),tokens[8].strip(),tokens[9].strip())
        tokensList.append(tokenItem)
    return tokensList

if __name__ == '__main__':
    tokens = []
    initialHoldings = {}
    startDate = '2008-01-01'
    endDate = '2008-12-31'
    for arg in sys.argv: 
        print arg
    if len(sys.argv) < 2:
        raise Exception('Invalid arguments')
    if (len(sys.argv)) >= 3:
        # COS.UN , 1000 , 28.8237380952 , 28823.7380952
        initialHoldings = parseInitialHoldings(sys.argv[2])
    if (len(sys.argv) >= 4):
        startDate = sys.argv[3]
    if (len(sys.argv) >= 5):
        endDate = sys.argv[4]
    if os.path.exists(sys.argv[1]):
        tokens = tokenize(sys.argv[1])
    transactions = createTransactionsFromTokens(tokens)
    transactionsMap = {}
    # the transactions per stock
    for transaction in transactions:
        if (transaction.symbol != ''):
            try:
                if transactionsMap[transaction.symbol] == None:
                    pass
            except:
                transactionsMap[transaction.symbol] = []
            transactionsMap[transaction.symbol].append(transaction)
    # 
    reportLine = ''
    holdingsLine = ''     
    currentCapitalGainLoss = 0
    for symbol in transactionsMap.keys():
        transactionsList = transactionsMap[symbol]
        initialHolding = None
        try:
            initialHolding = initialHoldings[symbol]
        except:
            pass
        r = EquityReport(symbol, '', getDate(startDate), getDate(endDate), initialHolding, 'CAD')
        r.addTransactions(transactionsList) 
        if not (r.isEmpty()):
            currentCapitalGainLoss += r.getRealizedCapitalGainsLosses()
            print r.toString()
            reportLine += r.toString() + '\n'
            if not (r.getResultingHoldings() == None):
                holdingsLine += r.getResultingHoldings().toString() + '\n'
    R = open(sys.argv[5]+'/Report_'+startDate+'_'+endDate+'.txt','w')
    R.write(reportLine)
    R.write('Capital Gain/Loss:' + str(currentCapitalGainLoss))
    H = open(sys.argv[5]+'/Holdings_'+startDate+'_'+endDate+'.txt','w')
    H.write(holdingsLine)
        
            